// RoleServiceImpl.java
package com.csxy.six.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.six.R;
import com.csxy.six.R2;
import com.csxy.six.entity.Role;
import com.csxy.six.entity.UserRole;
import com.csxy.six.exception.MyException;
import com.csxy.six.mapper.RoleMapper;
import com.csxy.six.mapper.UserRoleMapper;
import com.csxy.six.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public R2<List<Role>> getAllRoles() {
        return R2.ok(this.list());
    }

    @Override
    public R2<Void> createRole(Role role) {
        this.save(role);
        return R2.ok().message("角色创建成功");
    }

    @Override
    @Transactional
    public R2<Void> assignRole(Long userId, Long roleId) {
        // 检查角色是否存在
        Role role = this.getById(roleId);
        if (role == null) {
            throw new MyException(404, "角色不存在");
        }

        // 删除原有角色关联
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        userRoleMapper.delete(wrapper);

        // 添加新角色
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        userRoleMapper.insert(userRole);

        return R2.ok().message("角色分配成功");
    }
}